import argparse
# import jinja2
import yaml
import os


def to_makefile(makefile_inc: str, makefile_out: str, yaml_file: str, copy_include: bool = False):
    """Convert a YAML file to a Makefile fragment.

    Args:
        makefile_inc (str): Path to the Makefile fragment to include.
        makefile_out (str): Path to the Makefile fragment to write.
        yaml_file (str): Path to the YAML file to convert.
        copy_include (bool, optional): Copy the Makefile fragment to the output. Defaults to False.
    """
    # Load the YAML file.
    res = yaml.load(open(yaml_file, 'r'), Loader=yaml.FullLoader)
    # Load the makefile
    with open(makefile_out, 'w+') as file:
        file.write(
            '# This file is automatically generated by scripts/to_makefile.py\n')
        file.write('# Do not edit this file directly.\n')
        file.write(
            '# To make changes, edit the YAML file and run scripts/to_makefile.py\n')
        file.write('\n')
        if copy_include:
            file.write('# Include the original Makefile fragment.\n')
            file.write(open(makefile_inc, 'r').read())
            file.write('\n')
        else:
            file.write(
                '# Include the original Makefile fragment using include.\n')
            file.write('include ' + makefile_inc + '\n')
            file.write('\n')
        file.write(
            '# Below are the targets generated from the YAML file. #\n\n\n')

        # Write the contents from YAML file.
        for key in res:
            typ = key['type']
            job = key['filename'].replace('.mlir', f'-{typ}')
            file.write(f"{typ}-targets += {job}\n")
            file.write(f'{job}:\n')
            # todo: add warp
            for command in key['commands']:
                file.write('\t')
                if (command['env']):
                    file.write(command['env']+' ')
                file.write(command['exec'])
                file.write(command['args'].replace(
                    "${FILENAME}", key['filename']))
                if command['output'] == "STDOUT":
                    if command != key['commands'][-1]:
                        file.write(' | ')
                if command != key['commands'][-1]:
                    file.write(' \\')
                file.write(' \n')
            file.write('\n')


def main():
    to_makefile('makefile.inc', 'Makefile', 'example.yaml', copy_include=True)


if __name__ == "__main__":
    main()
